package com.captjack.distributedlock.configuration;

import com.captjack.distributedlock.lock.RedisDistributedLock;
import com.captjack.distributedlock.lock.ZookeeperDistributedLock;
import com.captjack.distributedlock.lock.redis.RedisDistributedLockImpl;
import com.captjack.distributedlock.lock.zookeeper.ZookeeperDistributedLockImpl;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 开启redis分布式锁配置
 *
 * @author Capt Jack
 * @date 2018/7/12
 */
@Configuration
public class DistributedLockConfiguration {

    /**
     * @return redis实现的锁
     */
    @Bean(name = "redis_distributed_lock")
    @ConditionalOnProperty(value = "distributed.lock.redis.enable", havingValue = "true")
    RedisDistributedLock redisDistributedLock(RedisTemplate redisTemplate) {
        return new RedisDistributedLockImpl(redisTemplate);
    }

    /**
     * @return zookeeper实现的锁
     */
    @Bean(name = "zookeeper_distributed_lock")
    @ConditionalOnProperty(value = "distributed.lock.zookeeper.enable", havingValue = "true")
    ZookeeperDistributedLock zookeeperDistributedLock(@Qualifier(value = "zookeeper_distributed_lock_curatorFramework") CuratorFramework curatorFramework) {
        return new ZookeeperDistributedLockImpl(curatorFramework);
    }

    /**
     * @return zookeeper客户端
     */
    @Bean(name = "zookeeper_distributed_lock_curatorFramework")
    @ConditionalOnProperty(value = "distributed.lock.zookeeper.enable", havingValue = "true")
    CuratorFramework curatorFramework(@Value("${distributed.lock.zookeeper.addresses}") String addresses) {
        // zookeeper重试机制
        RetryPolicy retryPolicy = new RetryNTimes(3, 1000);
        return CuratorFrameworkFactory.newClient(addresses, retryPolicy);
    }

}
